package com.xixi.core.rpc.server;

import com.xixi.core.rpc.RpcApplication;
import com.xixi.core.rpc.model.RpcRequest;
import com.xixi.core.rpc.model.RpcResponse;
import com.xixi.core.rpc.registry.LocalRegistry;
import com.xixi.core.rpc.serializer.CustomSerializer;
import com.xixi.core.rpc.serializer.CustomSerializerFactory;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author: zxh
 * @date: 2024/8/21 11:15
 * @description: HTTP请求处理
 */
public class CustomHttpServerHandler implements Handler<HttpServerRequest> {
	@Override
	public void handle(HttpServerRequest request) {
		// 指定序列化器，动态序列化器
		final CustomSerializer serializer = CustomSerializerFactory.getInstance(RpcApplication.getRpcConfig().getSerializer());

		// 记录日志
		System.out.println("Received request: " + request.method() + " " + request.uri());

		// 异步处理HTTP请求
		request.bodyHandler(body -> {
			byte[] bytes = body.getBytes();
			RpcRequest rpcRequest = null;
			try {
				rpcRequest = serializer.deserialize(bytes, RpcRequest.class);
			} catch (Exception e) {
				System.out.println("request serialize failed " + e.getMessage());
			}

			// 构造相应结果对象
			RpcResponse rpcResponse = new RpcResponse();
			// 如果请求为null，直接返回
			if (rpcRequest == null) {
				rpcResponse.setMessage("rpcRequest is null");
				doResponse(request, rpcResponse, serializer);
				return;
			}

			try {
				// 获取要调用的服务实现类，通过反射调用
				Class<?> implClass = LocalRegistry.get(rpcRequest.getServiceName());
				Method method = implClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
				Object result = method.invoke(implClass.newInstance(), rpcRequest.getArgs());
				// 封装返回结果
				rpcResponse.setData(result);
				rpcResponse.setDataType(method.getReturnType());
				rpcResponse.setMessage("ok");
			} catch (Exception e) {
				e.printStackTrace();
				rpcResponse.setMessage(e.getMessage());
				rpcResponse.setException(e);
			}
			// 响应
			doResponse(request, rpcResponse, serializer);
		});
	}


	/**
	 * 处理响应
	 *
	 * @param request     请求对象
	 * @param rpcResponse 响应数据
	 * @param serializer  序列化器
	 * @author zxh
	 * @CreateDate 2024/8/21
	 * @UpdateLog 2024/8/21 - []
	 */
	private void doResponse(HttpServerRequest request, RpcResponse rpcResponse, CustomSerializer serializer) {
		HttpServerResponse response = request.response();
		response.putHeader("Content-type", "application/json");
		try {
			// 序列化
			byte[] serialized = serializer.serialize(rpcResponse);
			response.end(Buffer.buffer(serialized));
		} catch (IOException e) {
			e.printStackTrace();
			response.end(Buffer.buffer());
		}
	}


}
